// #pragma once

// #define SIZE 1024
//  struct IO_FILE
// {
//     int flag; // 刷新方式
//     int fd;
//     char outbuffer[SIZE];
//     int cap;
//     int size;
// };
// typedef struct IO_FILE mFILE;
// mFILE *myfopen(const char *pathname, const char *mode);
// int myfwrite(const void *ptr, int num, mFILE *stream);
// void myfflush(mFILE*stream);
// void myclose(mFILE*stream);

#include "my_stdio.h"
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>  // 提供 write、fsync、close 的声明
#include <string.h>  // 如果用到 memcpy 等函数
mFILE *myfopen(const char *pathname, const char *mode)
{
    int fd = -1;
    if (strcmp(mode, "r")==0)
    {
        fd = open(pathname, O_RDONLY);
    }
    else if (strcmp(mode, "w")==0)
    {
        fd = open(pathname, O_CREAT | O_WRONLY, 0666);
    }
    else if (strcmp(mode, "a")==0)
    {
        fd = open(pathname, O_CREAT | O_RDWR, 0666);
    }
    else
        return NULL;
    if (fd < 0)
        return NULL;
    mFILE *mf = (mFILE *)malloc(sizeof(mFILE));
    if (mf == NULL)
        return NULL;
    mf->flag = 1;
    mf->fd = fd;
    mf->cap = SIZE;
    mf->size = 0;
    return mf;
}

void myfflush(mFILE *stream)
{
    if (stream->size > 0)
    {
        write(stream->fd, stream->outbuffer, stream->size);
        fsync(stream->fd);
        stream->size = 0;
    }
}

int myfwrite(const void *ptr, int num, mFILE *stream)
{
    memcpy(stream->outbuffer + stream->size, ptr, num);
    stream->size += num;
    if (stream->flag == 1 && stream->size > 0 && stream->outbuffer[stream->size - 1] == '\n')
    {
        myfflush(stream);
    }
    return num;
}
void myclose(mFILE *stream)
{
    if (stream->size > 0)
        myfflush(stream);
    close(stream->fd);
}